package com.in.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @Author Scott
 * @Date 2018-07-12 14:23
 * @Desc JWT工具类
 **/
public class JwtUtil {

    /**
     * Token有效期为24小时（Token在redis中缓存时间乘以2）
     */
    public static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     * @param response
     * @param code
     */
    public static void responseError(ServletResponse response, Integer code) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        // issues/I4YH95浏览器显示乱码问题
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        Result result = new Result();
        result.setCode(StatusCode.INTERNAL_SERVER_ERROR);
        OutputStream os = null;
        try {
            os = httpServletResponse.getOutputStream();
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(code);
            os.write(new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String account, String secret) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("account", account).build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getAccount(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("account").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     *
     * @param account 账号
     * @param secret  用户的密码
     * @return 加密的token
     */
    public static String sign(String userid, String account, String userName, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带account、userName信息
        return JWT.create().withClaim("userId", userid).
                withClaim("account", account).
                withClaim("nickname", userName).
                withExpiresAt(date).sign(algorithm);

    }

    /**
     * 根据request中的token获取用户账号
     *
     * @param request
     * @return
     * @throws
     */
    public static String getAccountByToken(HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        String account = getAccount(token);
        if (StringUtils.isBlank(account)) {
            throw new NullPointerException("未获取到用户");
        }
        return account;
    }

    /**
     * @Author liulianjia
     * @Description 根据request中的token获取用户id
     * @Date 2023/6/1 10:05
     **/
    public static String getUserIdByToken(HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.ACCESS_TOKEN);
        String userId = getUserId(token);
        if (StringUtils.isBlank(userId)) {
            throw new NullPointerException("未获取到用户");
        }
        return userId;
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的id
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的userName
     */
    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userName").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
